<?php
/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: dzf_base_model.php 4199 2014-10-09 08:36:47Z laoguozhang $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class dzf_base_model extends dzf_base_class
{

	/**
	 * 结果数据
	 * @var array
	 */
	public $data;

	/**
	 * showmessage方法句柄
	 * @var array
	 */
	public $showmessage = 'showmessage';

	/**
	 * @var dzf_base_application|mapi_app
	 */
	public $app;

	/**
	 * 用户数据
	 * @var array
	 */
	public $member;

	/**
	 * 用户组
	 * @var array
	 */
	public $group;

	/**
	 * setting数据
	 * @var array
	 */
	public $setting;

	/**
	 * 方法的参数集合
	 * @var array
	 */
	public $param = array();

	/**
	 * 构造函数
	 */
	public function __construct() {
		$this->app = DZF::app();
		parent::__construct();
	}

	/**
	 * 获取当前的 APP config的某个键值
	 * <code>
	 * EXP: $this->config('memory');
	 * RET: array('prefix' => ...)
	 *
	 * EXP: $this->config('cookie/cookiepre');
	 * RET: (string) adfs_
	 * </code>
	 * @param string $name
	 * @return Mixed
	 */
	public function config($key) {
	    $key = explode('/', $key);
	    $v = &$this->app->config;
	    foreach ($key as $k) {
	        if (!isset($v[$k])) {
	            return null;
	        }
	        $v = &$v[$k];
	    }
		return $v;
	}

	/**
	 * 获取当前 APP 全局setting 的某个键值
	 *
	 * <code>
	 * EXP: $this->setting('bbname');
	 * RET: (string) Discuz Board
	 *
	 * EXP: $this->setting('ec_credit/rank');
	 * RET: array(1=>4, 2=>11 ...)
	 *
	 * </code>
	 * @param string $name
	 * @return Mixed
	 */
	public function setting($name = null, $val = null) {
		if(isset($val)) {
			return $this->setvar($this->setting, $name, $val);
		}
		return $this->getvar($this->setting, $name);
	}

	/**
	 * table loader 获取某个 table 对象， 作用同 DZF::t($name)
	 * @param type $name table名
	 * @return dzf_base_table
	 */
	public function table($name) {
		return DZF::t($name);
	}

	/**
	 * 获取/设置Setting, 获取动自加载某个系统缓存，同时返回键值
	 * <code>
	 * EXP: $this->cache('grouptype');
	 * RET: arrary('first'=> ...)
	 *
	 * EXP: $this->cache('onlinelist/legend');
	 * RET: string(....)
	 *
	 * </code>
	 * @param type $name 缓存名称， 支持 缓存名称/缓存键值 这种形式
	 * @return mixed
	 */
	public function cache($name, $val = null) {
		if(isset($val)) {
			savecache($name, $val);
			$this->app->var['cache'][$name] = $val;
			return true;
		} else {
			if (!isset($this->app->var['cache'][$name])) {
				loadcache($name);
			}
			if($this->app->var['cache'][$name] === null) {
				return null;
			} else {
				return $this->app->var['cache'][$name];
			}
		}
	}

	/**
	 * 获取/设置当前 用户 的某个键值
	 *
	 * <code>
	 * EXP: $this->member('uid');
	 * RET: (string) 1
	 *
	 * EXP: $this->member('username');
	 * RET: admin
	 *
	 * </code>
	 * @param string $name
	 * @return Mixed
	 */
	public function member($name = null, $val = null){
		if(isset($val)) {
			return $this->setvar($this->member, $name, $val);
		} else {
			return $this->getvar($this->member, $name);
		}
	}

	/**
	 * 获取/设置当前 用户组 的某个键值
	 *
	 * <code>
	 * EXP: $this->group('id');
	 * RET: (string) 1
	 *
	 * EXP: $this->group('groupname');
	 * RET: 管理员
	 *
	 * </code>
	 * @param string $name
	 * @return Mixed
	 */
	public function group($name = null, $val = null){
		if(isset($val)) {
			return $this->setvar($this->group, $name, $val);
		} else {
			return $this->getvar($this->group, $name);
		}
	}

	/**
	 * 获取/设置当前 参数数据 的某个值
	 *
	 * <code>
	 * EXP: $this->param('key1');
	 * RET: (Mixed) val1
	 *
	 * EXP: $this->param('key1', 2); //设置key1的值为2
	 * RET: true
	 *
	 * </code>
	 * @param string $name
	 * @return Mixed
	 */
	public function param($name = null, $val = null){
		if(isset($val)) {
			return $this->setvar($this->param, $name, $val);
		}
		return $this->getvar($this->param, $name);
	}

	/**
	* 设置某变量的值
	* @param <string> $var 变量名
	* @param <string> $key 键
	* @param <string> $value 值
	* @return true
	*
	* @example
	* $this->setvar($this->member,, 'uid', 1); // $this->member['uid'] = 1;
	* setvar($this->member,, 'config/test/abc', 2); //$this->member['config']['test']['abc'] = 2;
	*
	*/
	public function setvar(&$var, $key, $value) {
		if(isset($key)) {
			$key = explode('/', $key);
			$p = &$var;
			foreach ($key as $k) {
				if(!isset($p[$k]) || !is_array($p[$k])) {
					$p[$k] = array();
				}
				$p = &$p[$k];
			}
			$p = $value;
		} else {
			$var = $value;
		}
		return true;
	}

	/**
	* 获取指定变量 $var 当中的某个数值
	* @example
	* $v = $this->getvar($this->member, 'uid'); // $v = $this->member['uid']
	* $v = $this->getvar($this->member, 'test/hello/ok');  // $v = $this->member['test']['hello']['ok']
	*
	* @param string $var
	* @param string $key
	*
	* @return mixed
	*/
	public function getvar(&$var, $key = null) {
		if(isset($key)) {
			$key = explode('/', $key);
			foreach ($key as $k) {
				if (!isset($var[$k])) {
					return null;
				}
				$var = &$var[$k];
			}
		}
		return $var;
	}


	public function showmessage() {
		if(!empty($this->showmessage) && is_callable($this->showmessage)) {
			$p = func_get_args();
			if(is_string($this->showmessage)) {
				$fn = $this->showmessage;
				switch (func_num_args()) {
					case 0:	return $fn();break;
					case 1:	return $fn($p[0]);break;
					case 2:	return $fn($p[0], $p[1]);break;
					case 3:	return $fn($p[0], $p[1], $p[2]);exit;break;
					case 4:	return $fn($p[0], $p[1], $p[2], $p[3]);break;
					case 5:	return $fn($p[0], $p[1], $p[2], $p[3], $p[4]);break;
					default: return call_user_func_array($this->showmessage, $p);break;
				}
			} else {
				return call_user_func_array($this->showmessage, $p);
			}
		} else {
			return func_get_args();
		}
	}

	

	/**
	 * 参数过滤和初始化，主方法体开始处执行
	 * @param array $parameters 参数数组
	 * @example
		protected function _init_parameters($parameters){
			$varname = array(
				//公共数据
				'member', 'group', 'forum', 'modnewthreads',
				//threa数据
				'subject', 'displayorder', 'save', 'ordertype', 'hiddenreplies',
				'allownoticeauthor', 'readperm', 'price', 'typeid', 'sortid',
				'publishdate', 'digest', 'moderated', 'tstatus', 'isgroup',
				'replycredit', 'closed', 'special', 'tags',
				//post数据
				'message','clientip', 'invisible', 'isanonymous', 'usesig',
				'htmlon', 'bbcodeoff', 'smileyoff', 'parseurloff', 'pstatus'
			);
			foreach($varname as $name) {
				if(!isset($this->params[$name]) && isset($parameters[$name])) {
					$this->params[$name] = $parameters[$name];
				}
			}
		}
	 */
	protected function _init_parameters($parameters){}

	/**
	* 设置cookie
	* @param $var - 变量名
	* @param $value - 变量值
	* @param $life - 生命期
	* @param $prefix - 前缀
	*/
	public function setcookie($var, $value = '', $life = 0, $prefix = 1, $httponly = false, $cookiedomain = '') {

		$config = $this->app->config['cookie'];

		$var = ($prefix ? $config['cookiepre'] : '').$var;
		$_COOKIE[$var] = $value;

		if($value == '' || $life < 0) {
			$value = '';
			$life = -1;
		}

		$life = $life > 0 ? TIMESTAMP + $life : ($life < 0 ? TIMESTAMP - 31536000 : 0);
		$path = $httponly && PHP_VERSION < '5.2.0' ? $config['cookiepath'].'; HttpOnly' : $config['cookiepath'];

		$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
		if(PHP_VERSION < '5.2.0') {
			setcookie($var, $value, $life, $path, $cookiedomain ? $cookiedomain : $config['cookiedomain'], $secure);
		} else {
			setcookie($var, $value, $life, $path, $cookiedomain ? $cookiedomain : $config['cookiedomain'], $secure, $httponly);
		}
	}
	

	/**
	 * 获取cookie
	 */
	public function getcookie($key, $prefix = 1) {
		$config = DZF::app()->config['cookie'];
		$key = ($prefix ? $config['cookiepre'] : '').$key;
		return $_COOKIE[$key];
	}
	
	/**
	 * 生成随机字符
	 * @param type $length
	 * @param type $numeric
	 * @return type
	 */
	public function random($length, $numeric = 0) {
		$seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
		$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
		if($numeric) {
			$hash = '';
		} else {
			$hash = chr(mt_rand(1, 26) + mt_rand(0, 1) * 32 + 64);
			$length--;
		}
		$max = strlen($seed) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $seed[mt_rand(0, $max)];
		}
		return $hash;
	}

}
